# 函数
def hello(name):
    return 'Hello, ' + name + '!'


print(hello('world'))
print(hello('Gumby'))


def fibs(num):
    result = [0, 1]
    for i in range(num - 2):
        result.append(result[-2] + result[-1])
    return result


print(fibs(10))


#
def square(x):
    'Calculates the square of the number x.'
    return x * x


#
print(square.__doc__)  # Calculates the square of the number x.
#
#
help(square)


# Help on function square in module __main__:
#
# square(x)
#     Calculates the square of the number x.


# 修改入参，影响原有变量
def change(n):
    n[0] = 'Mr. Gumby'


names = ['Mrs. Entity', 'Mrs. Thing']
change(names)
print(names)  # ['Mr. Gumby', 'Mrs. Thing']


# 关键字参数和默认值
def hello_1(greeting, name):
    print('{}, {}!'.format(greeting, name))


def hello_2(name, greeting):
    print('{}, {}!'.format(name, greeting))


hello_1('Hello', 'world')  # Hello, world!
hello_2('Hello', 'world')  # Hello, world!

hello_1(greeting="hello", name="world")
hello_1(name="world", greeting="hello")


# 参数默认值
def hello_3(greeting='Hello', name='world'):
    print('{}, {}!'.format(greeting, name))


hello_3()
hello_3(name="xxx")
hello_3(greeting="hi", name="xxx")


# 部分默认值
def hello_4(name, greeting='Hello', punctuation='!'):
    print('{}, {}{}'.format(greeting, name, punctuation))


# 任意参数
def print_params(*params):
    print(params)


# 是一个元组
print_params('Testing')  # ('Testing',)
print_params('1', '2', 3, 4)  # ('1', '2', 3, 4)


# , *参数使用元组收集
def print_params_2(title, *params):
    print(f"title={title},params={params}")


print_params_2('1', '2', 3, 4)  # title=1,params=('2', 3, 4)


def in_the_middle(x, *y, z):
    print(f'x={x}, y={y}, z={z}')


in_the_middle(1, 2, 3, 4, 5, z=7)  # x=1, y=(2, 3, 4, 5), z=7


# 要收集关键字参数，可使用两个星号
def print_params_3(**params):
    print(params)


# ** 使用字典收集
print_params_3(x=1, y=2, z=3)  # {'x': 1, 'y': 2, 'z': 3}


#
def print_params_4(x, y, z=3, *pospar, **keypar):
    print(f'x={x}, y={y}, z={z}')
    print(f'pospar={pospar}')
    print(f'keypar={keypar}')


print_params_4(1, 2, 3, 5, 6, 7, foo=1, bar=2)


# x=1, y=2, z=3
# pospar=(5, 6, 7)
# keypar={'foo': 1, 'bar': 2}


# 分配参数
def add(x, y):
    return x + y


params = (1, 2)
# 元组参数的解包 *tuple
print(add(*params))  # 3


# 字典的解包 **dict
def parse_dicts(greeting='Hello', name='world'):
    print('{}, {}!'.format(greeting, name))


params = {'name': 'Sir Robin', 'greeting': 'Well met'}
parse_dicts(**params)  # Well met, Sir Robin!


# 必须使用关键字参数 a=x,b=y
def with_stars(**kwds):
    print(kwds['name'], 'is', kwds['age'], 'years old')


def without_stars(kwds):
    print(kwds['name'], 'is', kwds['age'], 'years old')


args = {'name': 'Mr. Gumby', 'age': 42}

with_stars(**args)  # Mr. Gumby is 42 years old
without_stars(args)  # Mr. Gumby is 42 years old

with_stars(name="wwp", age=111)  # wwp is 111 years old

without_stars({"name": "xxx", "age": 121})  # xxx is 121 years old
